package org.charles.zhifou.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.charles.zhifou.common.annotation.AuthCheck;
import org.charles.zhifou.common.response.BaseResponse;
import org.charles.zhifou.common.response.ResponseCodeEnum;
import org.charles.zhifou.common.response.ResponseUtils;
import org.charles.zhifou.common.utils.HttpContextUtils;
import org.charles.zhifou.constant.UserConstant;
import org.charles.zhifou.enums.SqlSortOrderEnum;
import org.charles.zhifou.enums.UserRoleEnum;
import org.charles.zhifou.common.exception.ThrowUtils;
import org.charles.zhifou.model.dto.user.*;
import org.charles.zhifou.model.entity.User;
import org.charles.zhifou.model.vo.LoginUserVO;
import org.charles.zhifou.model.vo.UserVO;
import org.charles.zhifou.service.UserService;
import org.charles.zhifou.common.utils.SqlUtils;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <h1>用户接口</h1>
 *
 * @author charles
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户接口")
public class UserController {

    @Resource
    private UserService userService;

    // region 注册与登录

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求
     * @return 新注册用户 id
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public BaseResponse<?> userRegister(@Validated @RequestBody UserRegisterRequest userRegisterRequest) {
        // 提取参数
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        
        // 校验: 密码与确认密码必须相同
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ResponseCodeEnum.PARAMS_ERROR, "两次输入的密码不一致");

        // 封装参数
        User newUser = new User();
        newUser.setId(null);
        newUser.setUserAccount(userAccount);
        newUser.setUserPassword(userPassword);
        newUser.setUnionId(null);
        newUser.setMpOpenId(null);
        newUser.setUserName(userAccount);
        newUser.setUserAvatar(null);
        newUser.setUserProfile(null);
        newUser.setUserRole(UserRoleEnum.USER);
        String encryptedPassword = DigestUtils.md5DigestAsHex((UserConstant.PASSWORD_SALT + userPassword).getBytes());
        newUser.setUserPassword(encryptedPassword);
        
        Long newUserId = userService.saveUser(newUser);
        return ResponseUtils.success(newUserId);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求
     * @return 登录用户信息
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public BaseResponse<LoginUserVO> userLogin(@Validated @RequestBody UserLoginRequest userLoginRequest) {
        // 封装参数
        User user = new User();
        user.setId(null);
        user.setUserAccount(userLoginRequest.getUserAccount());
        user.setUnionId(null);
        user.setMpOpenId(null);
        user.setUserName(null);
        user.setUserAvatar(null);
        user.setUserProfile(null);
        user.setUserRole(null);
        String encryptedPassword = DigestUtils.md5DigestAsHex((UserConstant.PASSWORD_SALT + userLoginRequest.getUserPassword()).getBytes());
        user.setUserPassword(encryptedPassword);

        // 执行登录并返回登录用户信息
        LoginUserVO loginUserVO = userService.userLogin(user);
        return ResponseUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @return 是否注销成功
     */
    @PostMapping("/logout")
    @Operation(summary = "用户注销")
    public BaseResponse<Boolean> userLogout() {
        // 执行注销, 成功就返回 true
        Boolean result = userService.userLogout();
        return ResponseUtils.success(result);
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 当前登录用户信息
     */
    @GetMapping("/login_user")
    @Operation(summary = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser() {
        // 获取当前登录用户并返回
        User loginUser = userService.getLoginUser();
        LoginUserVO loginUserVO = LoginUserVO.entityToVo(loginUser);
        return ResponseUtils.success(loginUserVO);
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户 (仅管理员)
     *
     * @param userSaveRequest 创建用户请求
     * @return 新创建用户 id
     */
    @PostMapping("/add")
    @AuthCheck(neededRole = UserRoleEnum.ADMIN)
    @Operation(summary = "创建用户 (仅管理员)")
    public BaseResponse<Long> addUser(@Validated @RequestBody UserSaveRequest userSaveRequest) {
        // 封装参数
        User newUser = new User();
        newUser.setId(null);
        newUser.setUserAccount(userSaveRequest.getUserAccount());
        newUser.setUnionId(userSaveRequest.getUnionId());
        newUser.setMpOpenId(userSaveRequest.getMpOpenId());
        newUser.setUserName(userSaveRequest.getUserName());
        newUser.setUserAvatar(userSaveRequest.getUserAvatar());
        newUser.setUserProfile(userSaveRequest.getUserProfile());
        newUser.setUserRole(userSaveRequest.getUserRole());
        String encryptedPassword = DigestUtils.md5DigestAsHex((UserConstant.PASSWORD_SALT + userSaveRequest.getUserPassword()).getBytes());
        newUser.setUserPassword(encryptedPassword);

        Long newUserId = userService.saveUser(newUser);

        // 更新当前缓存的登录用户的信息


        return ResponseUtils.success(newUserId);
    }

    /**
     * 删除用户 (仅管理员)
     *
     * @param id 用户 id
     * @return 是否删除成功
     */
    @DeleteMapping("/delete")
    @AuthCheck(neededRole = UserRoleEnum.ADMIN)
    @Operation(summary = "删除用户 (仅管理员)")
    public BaseResponse<Boolean> deleteUser(
            @Min(value = 1, message = "id 必须大于 0")
            Long id
    ) {
        Boolean isSuccessful = userService.removeById(id);
        return ResponseUtils.success(isSuccessful);
    }

    /**
     * 根据 id 更新用户 (仅管理员)
     *
     * @param userUpdateRequest 更新用户请求
     * @return 是否更新成功
     */
    @PostMapping("/update")
    @AuthCheck(neededRole = UserRoleEnum.ADMIN)
    @Operation(summary = "根据 id 更新用户 (仅管理员)")
    public BaseResponse<Boolean> updateUserById(@Validated @RequestBody UserUpdateRequest userUpdateRequest) {
        // 更新用户
        User user = new User();
        user.setId(userUpdateRequest.getId());
        user.setUserAccount(userUpdateRequest.getUserAccount());
        user.setUnionId(userUpdateRequest.getUnionId());
        user.setMpOpenId(userUpdateRequest.getMpOpenId());
        user.setUserName(userUpdateRequest.getUserName());
        user.setUserAvatar(userUpdateRequest.getUserAvatar());
        user.setUserProfile(userUpdateRequest.getUserProfile());
        user.setUserRole(userUpdateRequest.getUserRole());
        String encryptedPassword = DigestUtils.md5DigestAsHex((UserConstant.PASSWORD_SALT + userUpdateRequest.getUserPassword()).getBytes());
        user.setUserPassword(encryptedPassword);
        
        Boolean isSuccessful = userService.updateUserById(user);
        return ResponseUtils.success(isSuccessful);
    }

    /**
     * 根据 id 获取用户 (仅管理员)
     *
     * @param id 用户 id
     * @return 用户信息 (完整)
     */
    @GetMapping("/get")
    @AuthCheck(neededRole = UserRoleEnum.ADMIN)
    @Operation(summary = "根据 id 获取用户 (仅管理员)")
    public BaseResponse<User> getUserById(
            @Min(value = 1, message = "id 必须大于 0")
            Long id
    ) {
        // 尝试获取, 获取不到就抛异常
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ResponseCodeEnum.NOT_FOUND_ERROR);
        return ResponseUtils.success(user);
    }

    /**
     * 根据 id 获取用户 VO
     *
     * @param id 用户 id
     * @return 用户信息 (部分)
     */
    @GetMapping("/get_vo")
    @Operation(summary = "根据 id 获取用户 VO")
    public BaseResponse<UserVO> getUserVOById(
            @Min(value = 1, message = "id 必须大于 0")
            Long id
    ) {
        // 尝试获取, 获取不到就抛异常
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ResponseCodeEnum.NOT_FOUND_ERROR);
        UserVO userVo = UserVO.entityToVo(user);
        return ResponseUtils.success(userVo);
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest 用户查询请求
     * @return 用户分页列表
     */
    @PostMapping("/list/page")
    @AuthCheck(neededRole = UserRoleEnum.ADMIN)
    @Operation(summary = "分页获取用户列表（仅管理员）")
    public BaseResponse<Page<User>> listUserByPage(@Validated @RequestBody UserQueryRequest userQueryRequest) {
        // 获取分页参数
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();

        // 分页查询并返回
        Page<User> userPage = userService.page(new Page<>(current, size), buildQueryWrapper(userQueryRequest));
        return ResponseUtils.success(userPage);
    }

    /**
     * 分页获取用户 VO 列表
     *
     * @param userQueryRequest 用户查询请求
     * @return 用户 VO 分页列表
     */
    @PostMapping("/list/page_vo")
    @Operation(summary = "分页获取用户 VO 列表")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@Validated @RequestBody UserQueryRequest userQueryRequest) {
        // 获取分页参数
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();

        // 查询 UserPage, 然后转换为 UserVOPage 返回
        Page<User> userPage = userService.page(new Page<>(current, size), buildQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        userVOPage.setRecords(userPage.getRecords().stream().map(UserVO::entityToVo).toList());

        return ResponseUtils.success(userVOPage);
    }


    /**
     * 更新个人信息
     *
     * @param userUpdateMyInfoRequest 更新个人信息请求
     * @return 是否更新成功
     */
    @PostMapping("/my/update_info")
    @Operation(summary = "用户更新个人信息")
    public BaseResponse<Boolean> updateMyInfo(@Validated @RequestBody UserUpdateMyInfoRequest userUpdateMyInfoRequest) {
        // 封装参数
        User user = new User();
        user.setId(userService.getLoginUser().getId());
        user.setUserAccount(null);
        user.setUserPassword(null);
        user.setUnionId(null);
        user.setMpOpenId(null);
        user.setUserName(userUpdateMyInfoRequest.getUserName());
        user.setUserAvatar(userUpdateMyInfoRequest.getUserAvatar());
        user.setUserProfile(userUpdateMyInfoRequest.getUserProfile());
        user.setUserRole(null);

        // 更新并返回
        Boolean isSuccessful = userService.updateById(user);

         // 更新 session 中的信息
        User loginUser = userService.getById(user.getId());
        HttpSession session = HttpContextUtils.getRequest().getSession();
        session.setAttribute(UserConstant.USER_LOGIN_STATE, loginUser);

        return ResponseUtils.success(isSuccessful);
    }

    // endregion
    /**
     * 获取查询 QueryWrapper
     * @param userQueryRequest 用户查询请求
     * @return 一个 QueryWrapper
     */
    public static QueryWrapper<User> buildQueryWrapper(UserQueryRequest userQueryRequest) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userQueryRequest == null) {
            return queryWrapper;
        }

        Long id = userQueryRequest.getId();
        String unionId = userQueryRequest.getUnionId();
        String mpOpenId = userQueryRequest.getMpOpenId();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        UserRoleEnum userRole = userQueryRequest.getUserRole();
        // 需要把小驼峰转为下划线
        String sortField = StrUtil.toUnderlineCase(userQueryRequest.getSortField());
        SqlSortOrderEnum sortOrder = userQueryRequest.getSortOrder();

        // 用 LambdaQueryWrapper 非常不方便, 因为根据排序字段获取 getter 需要使用反射
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(unionId), "union_id", unionId);
        queryWrapper.eq(StringUtils.isNotBlank(mpOpenId), "mp_open_id", mpOpenId);
        queryWrapper.eq(userRole != null, "user_role", userRole);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "user_profile", userProfile);
        queryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        // 如果 sortOrder 传入 null, 也会按升序排列
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), !SqlSortOrderEnum.DESC.equals(sortOrder), sortField);

        return queryWrapper;
    }
}
